<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入施工规范分类" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" highlight-current @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20">
        <!-- 搜索框 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
          <el-form-item label="施工规范分类" prop="commonConstructionId">
              <treeselect
              v-model="queryParams.commonConstructionId"
              :options="typeOptions"
              :normalizer="normalizer"
              placeholder="请选择施工规范分类"
              style="width:306px"
              />
            </el-form-item>
          <el-form-item label="标题" prop="commonConstructionTitle">
            <el-input v-model="queryParams.commonConstructionTitle" placeholder="请输入标题" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          
          <!-- <el-form-item label="所属节点名称" prop="commonConstructionTypeName">
            <el-input v-model="queryParams.commonConstructionTypeName" placeholder="请输入节点名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item> -->
           <!-- <div></div> -->
          <!-- <el-form-item label="质量问题等级" prop="questionLevel">
            <el-select v-model="queryParams.questionLevel" placeholder="请选择质量问题等级" clearable>
              <el-option v-for="dict in dict.type.list_quality_level" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item> -->
         
          <!-- <el-form-item label="数据来源" prop="dataSource">
            <el-input v-model="queryParams.dataSource" placeholder="请输入数据来源" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item> -->
          <el-form-item style="float:right">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 操作栏 -->
        <el-row :gutter="20" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['quality:questions:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['quality:questions:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['quality:questions:export']">导出</el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!-- 表格 -->
        <el-table v-loading="loading" :data="questionsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="标题" align="center" prop="commonConstructionTitle" />
          <el-table-column label="描述" align="center" prop="commonConstructionContent" />
          <el-table-column label="施工规范分类" align="center" prop="commonConstructionTypeName" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <!-- <el-table-column label="更新时间" align="center" prop="updateTime" /> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="LookUpdate(scope.row)"
                v-hasPermi="['quality:questions:edit']">查看</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['quality:questions:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['quality:questions:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改管理清单对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" class="dialogForm" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="commonConstructionTitle">
              <el-input :disabled="viewMode" v-model="form.commonConstructionTitle"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="施工规范分类" prop="commonConstructionId">
              <treeselect
              v-if="!viewMode"
              v-model="form.commonConstructionId"
              :options="typeOptions"
              :normalizer="normalizer"
              placeholder="请选择施工规范分类"
              />
              <el-input v-else :disabled="viewMode" v-model="form.commonConstructionTypeName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" >
              <el-input type="textarea" :disabled="viewMode" :rows="2" v-model="form.commonConstructionContent"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="施工规范文件">
              <FileUpload :fileSize="100" :viewMode="viewMode" @addNum="addNum" v-model="form.bizSafeAttaches"  @delNum="delNum"></FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listQuestions,
  getQuestions,
  delQuestions,
  addQuestions,
  updateQuestions,
  getListData,
  getQuestionsData,
  addData,
  updateData,
  delData
} from "@/api/quality/questions";
import {
  listTypeData,
} from "@/api/list/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "questions",
  dicts: ["list_quality_level", "list_quality_data_source"],
  components: {
    Treeselect,
  },
  data() {
    return {
      // 清单分类树选项
      typeOptions: [],
      viewMode:true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问题规范库表格数据
      questionsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeNo: null,
        questionInfo: null,
        questionOrigin: null,
        preventiveMeasures: null,
        questionLevel: null,
        normativeBasis: null,
        normativeInfo: null,
        dataSource: null,
        pic: [],
        sort: null,
        status: null,
        commonConstructionTypeName:null,
        commonConstructionTitle:null,
        commonConstructionId:null,
      },
      typeList:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        typeNo: [
          { required: true, message: "参建单位不能为空", trigger: "blur" },
        ],
        questionLevel: [
          { required: true, message: "质量问题等级不能为空", trigger: "blur" }
        ],
        dataSource: [
          { required: true, message: "数据来源不能为空", trigger: "blur" }
        ],
        normativeBasis: [
          { required: true, message: "规范依据不能为空", trigger: "blur" }
        ],
        normativeInfo: [
          { required: true, message: "规范内容不能为空", trigger: "blur" }
        ],
        questionInfo: [
          { required: true, message: "质量问题不能为空", trigger: "blur" }
        ],
        commonConstructionId: [
          { required: true, message: "施工规范分类不能为空", trigger: "blur" }
        ],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        commonConstructionTitle:[{ required: true, message: "标题不能为空", trigger: "blur" }]
      },
      //查看
      disabled: false,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "typeName",
      },
      typeNoData: {
        typeNo: null,
      },
      fit: 'contain',
      fileList:[],
      fileListData:null,
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    /** 查询管理清单列表 */
    getList() {
      this.loading = true;
      getListData(this.queryParams).then((response) => {
        this.questionsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getTreeselect()
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      listTypeData(this.queryParams).then((response) => {
        this.deptOptions = this.handleTree(response.rows, "id", "parentId");
        this.loading = false;
      });
      // treeselect(this.typeNoData).then((response) => {
      //   this.deptOptions = response.data;
      // });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.typeName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.typeNo = data.id;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typeNo: null,
        questionInfo: null,
        questionOrigin: null,
        preventiveMeasures: null,
        questionLevel: null,
        normativeBasis: null,
        normativeInfo: null,
        dataSource: null,
        pic: [],
        remark: null,
        sort: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        commonConstructionTitle:null,
        commonConstructionTypeName:null,
        commonConstructionId:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.deptName =undefined
      this.queryParams.typeNo = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.commonConstructionId = this.queryParams.typeNo;
      this.form.dataSource = "来源于施工规范文件";
      this.disabled = false
      this.viewMode = false
      this.open = true;
      this.getTreeselect()
      this.title = "添加施工规范文件";
    },
    // 查看
    LookUpdate(row) {
      const id = row.id || this.ids;
      getQuestionsData(id).then((response) => {
        this.form = response.data;
        if (this.form.bizSafeAttaches) {
          this.form.bizSafeAttaches.forEach(item => {
            item.name = item.displayName
            item.url = process.env.VUE_APP_MINIO_BASE_API+ "/" + item.bucket + "/" + item.realName;
          })
        }
        this.disabled = true;
        this.viewMode = true
        this.open = true;
        this.title = "查看施工规范文件";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = []
      this.reset();
      const id = row.id || this.ids;
      this.getTreeselect()
      getQuestionsData(id).then((response) => {
        this.form = response.data;
        if (this.form.bizSafeAttaches) {
          this.form.bizSafeAttaches.forEach(item => {
            item.name = item.displayName
            item.url = process.env.VUE_APP_MINIO_BASE_API+ "/" + item.bucket + "/" + item.realName;
          })
        }
        const data = {
          bucket:this.form.bucket,
          commonConstructionFileId:this.form.commonConstructionFileId,
          commonConstructionName:this.form.commonConstructionName,
          basePreviewUrl: process.env.VUE_APP_MINIO_BASE_API
        };
        // 将字符串拆分为数组
        const idArray = data.commonConstructionFileId.split(',');
        const nameArray = data.commonConstructionName.split(',');
        this.form.commonConstructionName = nameArray.map(name => `${data.basePreviewUrl}/${data.bucket}/${name}`);
        // 将每个ID转换为对象，组成新的数组
        const newArray = idArray.map((id, index) => ({ id, name: nameArray[index] }));
        // 更新数据
        this.fileList = newArray

        this.fileListData = process.env.VUE_APP_MINIO_BASE_API + "/" + this.form.bucket + "/" + this.fileList

        this.disabled = false
        this.viewMode = false
        this.open = true;
        this.title = "修改施工规范文件";
      });
    },
    //修改状态
    switchData(row) {
      var data = {
        status: row.status,
        id: row.id,
      };
      updateQuestions(data).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    // 
    addNum(data){
      this.fileList.push(data[0])
    },
    delNum(data){
      this.fileList.splice(data, 1);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            let lits = []
            let litsName = []
            this.fileList.forEach(item => {
              lits.push(item.id)
              litsName.push(item.name)
              });
              this.form.commonConstructionFileId = lits.toString()
              this.form.commonConstructionName = litsName.toString()
              this.form.bizSafeAttaches = null
            updateData(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let lits = []
            let litsName = []
            this.fileList.forEach(item => {
              lits.push(item.id)
              litsName.push(item.name)
              });
              this.form.commonConstructionFileId = lits.toString()
              this.form.commonConstructionName = litsName.toString()
              this.form.bizSafeAttaches = null
            addData(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除管理清单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delData(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'quality/questions/export',
        {
          ...this.queryParams,
        },
        `questions_${new Date().getTime()}.xlsx`
      );
    },
    /** 转换清单分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.typeName,
        children: node.children,
      };
    },
    /** 查询清单分类下拉树结构 */
    getTreeselect() {
      listTypeData().then((response) => {
        this.typeOptions = [];
        // const data = { parentId: 0, id: 0 , typeName: "顶级节点", children: [] };
        this.typeOptions = this.handleTree(response.rows, "id", "parentId");
        // this.typeOptions.push(data);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.dialogForm {
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 500px;
}
</style>
